const Koa = require('koa');
const os = require('os');
// 路由配置
const route = require('koa-route');
const multer = require('koa-multer');//加载koa-multer模块
const fs = require('fs')
// 允许静态资源被访问 直接在路径后面跟着资源名字即可
const static = require('koa-static')
const staticPath = '../static'
const path = require('path')
// 处理post请求
const koaBody = require('koa-body');
// 连接mongondb
const dbComAnime = require('./dbOprations/dbComAnime.js')
const dbComAnime2 = require('./dbOprations/dbComAnime.js')
const dbComAnime3 = require('./dbOprations/dbComAnime.js')
const dbComAnime4 = require('./dbOprations/dbComAnime.js')
const dbComAnime5 = require('./dbOprations/dbComAnime.js')
const dbComAnime6 = require('./dbOprations/dbComAnime.js')
const dbComAnime7 = require('./dbOprations/dbComAnime.js')
// AnimeIntro模板
const dbTermInfo = require('./dbOprations/term.js')
const dbCoachInfo = require('./dbOprations/coach.js')
// // detailPlots模板
const dbTeamInfo = require('./dbOprations/team.js')
// // cosersInfo模板
const dbOrderInfo = require('./dbOprations/order.js')
// // commentsInfo模板
const dbPlaceInfo = require('./dbOprations/place.js')
const dbUsersInfo = require('./dbOprations/user.js')
const dbCommentInfo = require('./dbOprations/comments.js')

const app = new Koa();

// mongoose AnimeIntro和charactersInfo和dbDetailPlots的Schema和modal创建
var Term = new dbTermInfo(dbComAnime)
var Coach = new dbCoachInfo(dbComAnime5)
var Team = new dbTeamInfo(dbComAnime2)
var Order = new dbOrderInfo(dbComAnime3)
var Place = new dbPlaceInfo(dbComAnime4)
var UsersInfo = new dbUsersInfo(dbComAnime6)
var Comment = new dbCommentInfo(dbComAnime7)

// 重定向
const redirect = ctx => {
  ctx.response.redirect('/');
};

const randomId = () => {
  var arr = ''
  for (let index = 0; index < 16; index++) {
    arr = arr + parseInt(Math.random() * 10)
  }
  return parseInt(arr)
}

// 获取用户信息
const userFind = async ctx => {
  ctx.response.type = 'json';
  await UsersInfo.UserFind(ctx.query.id).then((result) => {
    // 返回数据
    ctx.response.body = JSON.stringify(result)
  })
}

const usersFind = async ctx => {
  ctx.response.type = 'json';
  // 查询AnimeIntro  返回的结果是一个数组 
  // 因为是异步过程 得添加await
  await UsersInfo.UsersFind(ctx.query).then((result) => {
    // 返回数据
    ctx.response.body = JSON.stringify(result)
  })
}

const beMember = async ctx => {
  ctx.response.type = 'json';
  await UsersInfo.beMember(ctx.request.body).then((result) => {
    // 返回数据
    ctx.response.body = JSON.stringify(result)
  })
}

const income = async ctx => {
  ctx.response.type = 'json';
  // 查询AnimeIntro  返回的结果是一个数组 
  // 因为是异步过程 得添加await
  await UsersInfo.income(ctx.query).then((result) => {
    // 返回数据
    ctx.response.body = JSON.stringify(result)
  })
}


const addUser = async ctx => {
  ctx.response.type = 'json';
  // 因为是异步方法实现同步操作 得添加await
  await UsersInfo.addUser(ctx.request.body).then((result) => {
    // 返回数据
    ctx.response.body = JSON.stringify(result)
  })
}




// 课程获取
const termsFind = async ctx => {
  ctx.response.type = 'json';
  await Term.termsFind(ctx.query).then((result) => {
    // 返回数据
    ctx.response.body = JSON.stringify(result)
  })
}

const addTerm = async ctx => {
  console.log(ctx.request.body)
  ctx.response.type = 'json';
  ctx.request.body.id = randomId()
  // 课程添加
  await Term.addTerm(ctx.request.body)
  await Coach.coachFind(ctx.request.body.userId).then((res) => {
    ctx.request.body.res = res
  })
  // 教练的最低课程价格更新
  await Coach.minUpdate(ctx.request.body).then((res) => {
    ctx.response.body = JSON.stringify(
      { id: ctx.request.body.id }
    )
  })
}

const TermUpload = async function (ctx) {
  const filePaths = [];
  const files = ctx.request.files || {};
  var fileName = randomId() + '.png'
  for (let key in files) {
    const file = files[key];
    const filePath = path.join(__dirname, '../static/img/' + fileName);
    const reader = fs.createReadStream(file.path);
    const writer = fs.createWriteStream(filePath);
    reader.pipe(writer);
    filePaths.push(filePath);
  }
  ctx.request.body.imgUrl = fileName
  ctx.request.body.id = parseInt(ctx.request.body.id)
  // 图片地址插入表单
  await Term.addTerm(ctx.request.body).then((result) => {
    // 返回数据
    ctx.response.body = JSON.stringify(result)
  })
};

//coach
const coachsFind = async ctx => {
  ctx.response.type = 'json';
  // 查询AnimeIntro  返回的结果是一个数组 
  // 因为是异步过程 得添加await
  await Coach.coachsFind(ctx.query).then((result) => {
    // 返回数据
    ctx.response.body = JSON.stringify(result)
  })
}

const addCoach = async ctx => {
  ctx.response.type = 'json';
  // 查询AnimeIntro  返回的结果是一个数组 
  // 因为是异步过程 得添加await
  await Coach.addCoach(ctx.request.body).then((res) => {
    ctx.response.body = JSON.stringify(res)
  })
}


var whichDay = function (num) {
  var date = new Date()
  date.setDate(date.getDate() + num)
  switch (date.getDay()) {
    case 0:
      return '周一'
    case 1:
      return '周二'
    case 2:
      return '周三'
    case 3:
      return '周四'
    case 4:
      return '周五'
    case 5:
      return '周六'
    case 6:
      return '周日'
  }
}
var week = function (num) {
  var date = new Date()
  date.setDate(date.getDate() + num)
  return `${date.getMonth() + 1}-${date.getDate()}`
}

//team
const teamFind = async ctx => {
  ctx.response.type = 'json';
  await Team.teamFind(ctx.query).then((res) => {
    ctx.response.body = JSON.stringify(res)

  })
}

const teamsFind = async ctx => {
  ctx.response.type = 'json';
  // 查询AnimeIntro  返回的结果是一个数组 
  // 因为是异步过程 得添加await
  await Team.teamsFind(ctx.query).then((result) => {
    var data = [
      {
        week: '今天',
        date: week(0),
        content: []
      },
      {
        week: '明天',
        date: week(1),
        content: []
      },
      {
        week: whichDay(1),
        date: week(2),
        content: []
      },
      {
        week: whichDay(2),
        date: week(3),
        content: []
      },
      {
        week: whichDay(3),
        date: week(4),
        content: []
      },
      {
        week: whichDay(4),
        date: week(5),
        content: []
      },
      {
        week: whichDay(5),
        date: week(6),
        content: []
      },
    ]
    var date = new Date()
    date.setHours(0)
    date.setMinutes(0)
    date.setSeconds(0)
    for (let index = 0; index < result.length; index++) {
      if (result[index].participant.indexOf(ctx.query.userId) !== -1) {
        result[index].__v = 1
      }
      let day = Math.abs((result[index].time.getTime() - date.getTime()) / 1000)
      day = parseInt(day / (24 * 60 * 60))
      switch (day) {
        case 0:
          data[0].content.push(result[index])
          break;
        case 1:
          data[1].content.push(result[index])
          break;
        case 2:
          data[2].content.push(result[index])
          break;
        case 3:
          data[3].content.push(result[index])
          break;
        case 4:
          data[4].content.push(result[index])
          break;
        case 5:
          data[5].content.push(result[index])
          break;
        case 6:
          data[6].content.push(result[index])
          break;
      }
    }
    // 返回数据
    ctx.response.body = JSON.stringify(data)
  })
}

const addTeam = async ctx => {
  ctx.response.type = 'json';
  ctx.request.body.id = randomId()
  // console.log(new Date(ctx.request.body.date + ' '+ ctx.request.body.time))
  await Team.addTeam(ctx.request.body).then((rsl) => {
    ctx.response.body = JSON.stringify(
      { id: ctx.request.body.id }
    )
  })
}

const TeamUpload = async function (ctx) {
  const filePaths = [];
  const files = ctx.request.files || {};
  var fileName = randomId() + '.png'
  for (let key in files) {
    const file = files[key];
    const filePath = path.join(__dirname, '../static/img/' + fileName);
    const reader = fs.createReadStream(file.path);
    const writer = fs.createWriteStream(filePath);
    reader.pipe(writer);
    filePaths.push(filePath);
  }
  ctx.request.body.imgUrl = fileName
  ctx.request.body.id = parseInt(ctx.request.body.id)
  await Team.addTeam(ctx.request.body).then((result) => {
    // 返回数据
    ctx.response.body = JSON.stringify(result)
  })
};

const participate = async ctx => {
  ctx.response.type = 'json';
  // 查询AnimeIntro  返回的结果是一个数组 
  // 因为是异步过程 得添加await

  await Team.participate(ctx.query).then((result) => {
    // 返回数据
    ctx.response.body = JSON.stringify(result)
  })
}

//order
const orderFind = async ctx => {
  ctx.response.type = 'json';
  await Order.orderFind(ctx.query).then((result) => {
    // 返回数据
    ctx.response.body = JSON.stringify(result)
  })
}

const addOrder = async ctx => {
  ctx.response.type = 'json';
  await Order.addOrder(ctx.request.body)
  await UsersInfo.income({ coachId: ctx.request.body.coachId, money: ctx.request.body.sum })
  await UsersInfo.income2({ coachId: ctx.request.body.coachId, money: ctx.request.body.sum }).then((result) => {
    // 返回数据
    ctx.response.body = JSON.stringify(result)
  })

}

const predict = async ctx => {
  ctx.response.type = 'json';
  if (ctx.request.time) {
    ctx.request.time = new Date(ctx.request.time)
  }
  await Order.predict(ctx.query).then((result) => {
    // 返回数据
    ctx.response.body = JSON.stringify(result)
  })
}

const complete = async ctx => {
  ctx.response.type = 'json';
  // 查询AnimeIntro  返回的结果是一个数组 
  // 因为是异步过程 得添加await
  var result = []
  await Order.complete(ctx.query).then((res) => {
    result = res
  })
  if (ctx.query.coachId && result[0].userReduce) {
    await Coach.lessonNumberUpdate(ctx.query.coachId)
  } else if (ctx.query.userId && result[0].coachReduce) {
    await Coach.lessonNumberUpdate(result[0].coachId)
  }
  if (ctx.query.userId) {
    await Order.userUpdate(result).then((rsl) => {
      ctx.response.body = JSON.stringify({})
    })
  } else {
    await Order.coachUpdate(result).then((rsl) => {
      ctx.response.body = JSON.stringify({})
    })
  }
}

// place\
const placeFind = async ctx => {
  ctx.response.type = 'json';
  // 查询AnimeIntro  返回的结果是一个数组 
  // 因为是异步过程 得添加await

  await Place.placeFind(ctx.query).then((result) => {
    // 返回数据
    ctx.response.body = JSON.stringify(result)
  })
}

const placesFind = async ctx => {
  ctx.response.type = 'json';
  // 查询AnimeIntro  返回的结果是一个数组 
  // 因为是异步过程 得添加await

  await Place.placesFind(ctx.query).then((result) => {
    // 返回数据
    ctx.response.body = JSON.stringify(result)
  })
}

const placeAdd = async ctx => {
  ctx.response.type = 'json';

  ctx.request.body.id = randomId()

  await Place.placeAdd(ctx.request.body).then((rsl) => {
    ctx.response.body = JSON.stringify(
      { id: ctx.request.body.id }
    )
  })
}

const placeUpload = async function (ctx) {
  const filePaths = [];
  const files = ctx.request.files || {};
  var fileName = randomId() + '.png'
  for (let key in files) {
    const file = files[key];
    const filePath = path.join(__dirname, '../static/img/' + fileName);
    const reader = fs.createReadStream(file.path);
    const writer = fs.createWriteStream(filePath);
    reader.pipe(writer);
    filePaths.push(filePath);
  }
  ctx.request.body.imgUrl = fileName
  ctx.request.body.id = parseInt(ctx.request.body.id)
  await Place.placeAdd(ctx.request.body).then((result) => {
    // 返回数据
    ctx.response.body = JSON.stringify(result)
  })
};

//comment
const commentsFind = async ctx => {
  ctx.response.type = 'json';
  // 因为是异步过程 得添加await
  await Comment.CommentsFind(ctx.query).then((result) => {
    // 返回数据
    ctx.response.body = JSON.stringify(result)
  })
}

const addComment = async ctx => {
  ctx.response.type = 'json';
  // 查询AnimeIntro  返回的结果是一个数组 
  // 因为是异步过程 得添加await
  ctx.request.body.id = randomId()
  await Comment.addComment(ctx.request.body).then((res) => {
    ctx.response.body = JSON.stringify(ctx.request.body.id)
  })
  if (ctx.request.body.userId !== ctx.request.body.coachId) {
    var coach = {}
    await Coach.coachFind(ctx.request.body.coachId).then((res) => {
      coach = res[0]
    })
    await Coach.priaseDegree(ctx.request.body, coach).then((res) => {
      ctx.response.body = JSON.stringify({ success: true })
    })
  } else {
    ctx.response.body = JSON.stringify({ success: false })
  }

}

const commentUpload = async function (ctx) {
  const filePaths = [];
  const files = ctx.request.files || {};
  var fileName = randomId() + '.png'
  for (let key in files) {
    const file = files[key];
    const filePath = path.join(__dirname, '../static/img/' + fileName);
    const reader = fs.createReadStream(file.path);
    const writer = fs.createWriteStream(filePath);
    reader.pipe(writer);
    filePaths.push(filePath);
  }
  ctx.request.body.imgUrl = fileName
  ctx.request.body.id = parseInt(ctx.request.body.id)
  await Comment.addComment(ctx.request.body).then((result) => {
    // 返回数据
    ctx.response.body = JSON.stringify(result)
  })
};


const main = ctx => {
  ctx.response.body = '呵呵'
};



// 使用中间件
app.use(static(
  path.join(__dirname, staticPath)
))
app.use(koaBody({ multipart: true }));
app.use(route.get('/', main));
app.use(route.get('/temp', redirect));
app.use(route.get('/api/getUser', userFind));
app.use(route.get('/api/getUsers', usersFind));
app.use(route.post('/api/beMember', beMember));
app.use(route.post('/api/addUser', addUser));
app.use(route.get('/api/income', income));

app.use(route.get('/api/termsFind', termsFind));
app.use(route.post('/api/addTerm', addTerm));
app.use(route.post('/api/TermUpload', TermUpload));

app.use(route.get('/api/coachsFind', coachsFind));
app.use(route.post('/api/addCoach', addCoach));

app.use(route.get('/api/teamFind', teamFind));
app.use(route.get('/api/teamsFind', teamsFind));
app.use(route.post('/api/addTeam', addTeam));
app.use(route.post('/api/TeamUpload', TeamUpload));
app.use(route.get('/api/participate', participate));

app.use(route.get('/api/orderFind', orderFind));
app.use(route.post('/api/addOrder', addOrder));
app.use(route.get('/api/predict', predict));
app.use(route.get('/api/complete', complete));

app.use(route.get('/api/placeFind', placeFind));
app.use(route.get('/api/placesFind', placesFind));
app.use(route.post('/api/placeAdd', placeAdd))
app.use(route.post('/api/placeUpload', placeUpload));


app.use(route.get('/api/commentsFind', commentsFind));
app.use(route.post('/api/addComment', addComment));
app.use(route.post('/api/commentUpload', commentUpload));

app.listen(2334, () => {
  console.log('server start')
});
